package com.nexus.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Springboot上下文
 *
 * @Date 2025/9/24 21:05
 * @Author luzhengning
 **/
@Component
@Slf4j
public class SpringContextHolder implements ApplicationContextAware, InitializingBean {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        log.info("SpringContextHolder初始化完成，ApplicationContext: {}",
                applicationContext != null ? "已设置" : "未设置");
    }

    public static void printContextInfo() {
        log.info("当前ApplicationContext: {}", applicationContext);
        if (applicationContext != null) {
            log.info("Bean定义数量: {}", applicationContext.getBeanDefinitionCount());
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}